package com.itheima.tanhua.member.interceptor;

import cn.hutool.jwt.JWT;
import com.itheima.tanhua.base.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    private String key = "1234";
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(token==null){
            throw new LoginException("请先登录！");
        }
        if(!redisTemplate.hasKey(token)){
            throw  new LoginException("token过期！");
        }
        boolean verify = JWT.of(token).setKey(key.getBytes()).verify();
        if(!verify){
            throw new LoginException("token错误！");
        }
        if(redisTemplate.getExpire(token, TimeUnit.HOURS)<12){
            redisTemplate.expire(token,7,TimeUnit.DAYS);
        }
        String memberId = (String) JWT.of(token).getPayload("id");
        BaseContext.setCurrentId(memberId);
        return true;
    }
}